package com.woniuxy.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniuxy.pojo.Employee;
import com.woniuxy.pojo.MailConstants;
import com.woniuxy.pojo.MailLog;
import com.woniuxy.service.IEmployeeService;
import com.woniuxy.service.IMailLogService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Description:邮件发送定时任务
 * @author: ykq11  <br/>
 * Date: 2022/2/20:17:55  <br/>
 */
@Component
public class MailTask {
    @Autowired
    private IMailLogService mailLogService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    private static final Logger log = LoggerFactory.getLogger(MailTask.class);

    @Scheduled(cron = "0/30 * * * * ?")
    public void mailTask() {
       // log.info("开始执行定时任务(重新投递消息)");
        List<MailLog> mailLogList = mailLogService.list(new QueryWrapper<MailLog>().eq("status", 0).lt("tryTime", LocalDateTime.now()));
            mailLogList.forEach(mailLog -> {
                // 如果重试次数超过三次，更新状态为投递失败，不在重试
                if (3 <= mailLog.getCount()) {
                    mailLogService.update(new UpdateWrapper<MailLog>().set("status", 2).eq("msgId", mailLog.getMsgId()));
                    //log.info("超过最大重试次数, 消息投递失败, msgId: {}", mailLog.getMsgId());
                }else {
                    mailLogService.update(new UpdateWrapper<MailLog>()
                            .set("count", mailLog.getCount() + 1)
                            .set("updateTime", LocalDateTime.now())
                            .set("tryTime", LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT)));
                    Employee employee = employeeService.getEmp(mailLog.getEid()).get(0);
                    rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY, employee, new CorrelationData(mailLog.getMsgId()));
                }
            });
       // log.info("定时任务执行结束(重新投递消息)");
    }
}
